$(function(){
    var URLS = 'URLS';
    //输入框自动完成
    var getURLs = function(){
        var urls = localStorage.getItem(URLS);
        
        if(urls){
            return JSON.parse(urls);
        }
        return [];
    };
    var engine = new Bloodhound({
        local: getURLs(),
        identify: function(obj) { 
            
            return obj 
        },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        datumTokenizer: Bloodhound.tokenizers.whitespace
    });
   
    var addUrls = function(url){
         var urls = localStorage.getItem(URLS);
         if(!urls){
             urls = [];
         }else{
            urls = JSON.parse(urls);
         }
         if(urls.indexOf(url)===-1){
            urls.push(url)
         }
         //添加到source
         engine.add(url);
         //本地存储
         localStorage.setItem(URLS,JSON.stringify(urls));
    }
    var Matcher = function(strs){
        return function findMatches(q, cb) {
            var matches, substringRegex;
            matches = [];
            substrRegex = new RegExp(q, 'i');
            $.each(strs, function(i, str) {
                if (substrRegex.test(str)) {
                  matches.push(str);
                }
            });

            cb && cb(matches);
        };
    }
    
    //重写search方法使其能够模糊匹配
    engine.search=function(query, sync,async){
        Matcher(engine.all())(query,sync);
    }
    
    $('[data-provide="typeahead"]').typeahead({
        highlight : true,
        hint :true,
        minLength:1
    },{
        limit: 200,
        source: engine,
        name: 'URLs'
    });

    //JSON Editor
    var bodyContainer = document.getElementById("txt_request_body");
    var JSONEditorOptions = {
        search:false,
        modes:['tree','view','form','code','text'],
    };
    
    var bodyEditor = new JSONEditor(bodyContainer, JSONEditorOptions);

    var headerContainer = document.getElementById('txt_request_header');
   
    var headerJSON = {
        'Content-Type':'application/json'
    }
    var headerEditor = new JSONEditor(headerContainer, JSONEditorOptions,headerJSON);
    

    $('#method_menu .method').on('click',function(){
        $('#txt_method').text($(this).text().trim());
    });

     $('#txt_url').on('keydown',function(e){
        if(e.keyCode === 13){
            $('#btn_send').click();
        }
    });

    $('#btn_send').on('click',function(){
        $('#txt_response_body').text('');
        $('#txt_response_header').text('');
        $('#txt_status').text('');

        var reqHeaders = headerEditor.get();
        var reqMethod =  $('#txt_method').text().trim();
        var reqBody = bodyEditor.get();        
        var reqURL = $('#txt_url').val().trim();
        var dataType = $('#data_type').text().trim();
        if(!reqURL){
            alert('请输入Api URL');
            return ;
        }else if(reqURL.indexOf('http://') === -1 && reqURL.indexOf('https://') === -1){
            alert('请输入正确的Api URL');
            return ;
        }
        var options = {
            url:reqURL,
            type:reqMethod,
            data:JSON.stringify(reqBody),
            dataType:dataType,
            success:function(rest,status,xhr){
                if(rest){
                    try {
                        $('#txt_response_body').text(JSON.stringify(rest,null,2));
                    } catch (error) {
                        $('#txt_response_body').text(rest)
                    }                        
                }
            },
            error:function(err){
                try {
                    $('#txt_response_body').text(JSON.stringify(err.responseJSON,null,2));
                } catch (error) {
                    $('#txt_response_body').text(err.responseText)
                }
            },
            complete:function(xhr){
                
                addUrls(reqURL);
                $('#txt_status').text(`${xhr.status} ${xhr.statusText}`);

                var ResponseHeader = xhr.getAllResponseHeaders();
                
                var headersText = [];
                headersText.push(`Request URL : ${reqURL}`);
                headersText.push(`Request Method : ${reqMethod}`);
                headersText.push(`Status Code : ${xhr.status} ${xhr.statusText}`);
                headersText.push(`dataType : ${dataType}`);
                headersText.push(`\nRequest Header `);
                for(var k in reqHeaders){
                     headersText.push(k +' : '+reqHeaders[k]);
                }
                headersText.push('\nRequest body');
                headersText.push(JSON.stringify(reqBody,null,2));
                
                headersText.push(`\nResponse Header`);
                headersText.push(ResponseHeader);

                headersText.push('\nResponse Text');
                headersText.push(JSON.stringify(xhr.responseJSON,null,2));
                
                $('#txt_response_header').text(headersText.join('\n'));
                
                
            }
        }
        options.beforeSend = function(xhr){
            
            for(var k in reqHeaders){
                xhr.setRequestHeader(k,reqHeaders[k])
            }
            
        }
        $.ajax(options);
    });

    $('.content_type').on('click',function(){
        var contentType = $(this).text().trim();
        var headers = headerEditor.get();
        if(headers){
            headers['Content-Type'] = contentType;
        }
        headerEditor.set(headers);
        $('#btn_request_header a').tab('show')
    });
    $('.data_type').on('click',function(){
       $('#data_type').text($(this).text().trim());
    });
});